package com.manager.commons.utils;

//                   _ooOoo_    
//                  o8888888o    
//                  88" . "88    
//                  (| -_- |)    
//                   O\ = /O    
//               ____/'---'\____    
//              /. '\\| : |//' .\    
//             // \\||| : |||// \\   
//            // _|||||-:-|||||_ \\    
//           // | | \\\ - /// | | \\
//           || |_| ''\---/'' |_| || 
//            \ .-\___/'-'\___/-. /    
//          ___\. .' /--.--\ '. ./___    
//        .""'< `.___\_<|>_/___.' >'"".    
//       | |: `- \`.|'\ _ /'|.`/ -` :| |    
//        \ \ `-. \_ __\ /__ _/ .-` / /    
//======'-.___`-.___\_______/___.-`___.-'======    
//                   '=---='    
//.................................................    
//写一哈代码，你就青叫唤；信龟儿设计，你逗是傻逼。
//永无Bug，啷个可能！求佛主保佑也没球用！

import java.util.Random;

/**
 * PasswordUtil(密码)
 * @author H
 * @version V1.0
 */
public class PasswordUtil {

	private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	private static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
	private static final String NUMBERS = "0123456789";
	private static final String SPECIAL_CHARS = "!@#$%^&*_=+-/";
	private static final String ALL_CHARS = UPPER + LOWER + NUMBERS + SPECIAL_CHARS;
	private static final String[] array = { UPPER, LOWER, NUMBERS, SPECIAL_CHARS };

	/**
	 * 生成随机密码
	 * @param length 如果值小于8，将自动补足8位，密码最少8位
	 * @return
	 */
	public static String generate(int length) {
		StringBuilder password = new StringBuilder();
		if (length < 8) {
			length = 8;
		}
		for (int i = 0; i < 4; i++) {
			int index = new Random().nextInt(4);
			password.append(randomStr(length / 4, array[index]));
		}
		String pwd = password.toString();
		if (pwd.length() != length) {
			password.append(randomStr(length - pwd.length(), ALL_CHARS));
		}
		return password.toString();
	}

	/**
	 * 随机字符串
	 * @param length
	 * @param str
	 * @return
	 */
	public static String randomStr(int length, String str) {
		Random random = new Random();
		StringBuilder password = new StringBuilder();
		for (int i = 0; i < length; i++) {
			int index = random.nextInt(str.length());
			password.append(str.charAt(index));
		}
		return password.toString();
	}
}